/**
 * Created by john on 2018/3/28.
 */
var express = require('express');
var router = express.Router();
const USER = require("../src/user");
const COMM = require("../src/comm");
var qs = require("qs");

/*pc端页面得路由*/
const CreateToken = require("../src/token"); //创建token
const myCache = require("../src/cache");    //缓存
const VALID = require("../config/valid");   //防止其他的盗用
const  VCODE =require("../config/code"); //错误码


function  checkApp(req,res,next) {
    var _token = req.query._token || req.body._token || "";
    var _app = req.query._app || req.body._app || "";
    var _cd = req.query._cd || req.body._cd || "";
    //校验，不能让别人的服务接入
    if(_app && VALID[_app] && _cd){
        res.locals._token = _token;
        res.locals._app = _app;
        res.locals._cd = _cd;
        next();
    }else{
        res.status(403).send('Forbidden,确认参数是否正确');
    }
}

//回调中加入Token,需要防止重复的token
function  formatCdUrl(url,_token) {
    var arr = url.split("?");
    var obj = qs.parse(arr[1]);
    obj._token = _token;
    url = arr[0] + "?" + qs.stringify(obj);
    console.log(url);
    return url;
}

router.get('/', function(req, res, next) {
    res.redirect("/admin");
});
//登录页面
router.get('/login', checkApp,function(req, res, next) {
    var _token = req.session.token;
    console.log("login:sesson",_token);
    if(_token){
        var cache = myCache.get(_token);
        if(cache){
            //session里面有token 且缓存里面也有
            var _app = res.locals._app;
            var _cd = res.locals._cd;
            var url = decodeURIComponent(_cd); //解码
            cache._app[_app] = "";
            myCache.set(_token,cache); //加入记录，用于退出时候清除记录
            if(url.indexOf(VALID[_app].key) != -1){
                url = formatCdUrl(url,_token); //回调中加入Token
                res.redirect(url);
            }else{
                res.status(403).send('Forbidden,确认参数是否正确');
            }

        }else{
            req.session.token = null;
            res.render('login');
        }
    }else{
        res.render('login');
    }

});

//普通页面回调，意图获取用户信息
router.get('/login/normal', checkApp,function(req, res, next) {
    var _token = req.session.token;
    console.log("login:sesson",_token);
    //session里面有token 且缓存里面也有
    var _app = res.locals._app;
    var _cd = res.locals._cd;

    var url = decodeURIComponent(_cd); //解码
    console.log("step1"+url);
    if(_token){
        var cache = myCache.get(_token);
        if(cache){
            cache._app[_app] = "";
            myCache.set(_token,cache); //加入记录，用于退出时候清除记录
            if(url.indexOf(VALID[_app].key) != -1){
                url = formatCdUrl(url,_token); //回调中加入Token
                res.redirect(url);
            }else{
                res.redirect(url);
            }
        }else{
            req.session.token = null;
            res.redirect(url);
        }
    }else{
        res.redirect(url);
    }

});


router.get('/register',checkApp, function(req, res, next) {
    res.render('register');
});

//注册接口
router.post('/api/register', function(req, res, next) {
    var params = req.body;
    params.level = 1; //强制注册为普通用户，只有后台管理能有权限将某个用户的等级升高
    params.type = 1;
    var url =  '/login?_app='+ params._app +'&_cd='+ params._cd;
    if(!params._app){
        url = '/self' + url;
    }
    if(!params.password || params.password.length < 6 ){
        res.send(VCODE.param);
        return ;
    }
    USER.signup(params).then(function (ret) {
        var data = {data:{"_url":url}}
        data = Object.assign(data,VCODE.success);
        res.send(data);
    }).catch(function (ret) {
        res.send(ret);
    })
});


//登录接口
router.post('/api/login', function(req, res, next) {
    var _app = req.body._app ||'';
    var _cd = req.body._cd || '';
    if(_app && VALID[_app] && _cd){
        var url = decodeURIComponent(_cd); //解码
       if(url.indexOf(VALID[_app].key) != -1){
           var _token = CreateToken();
           url = formatCdUrl(url,_token); //回调中加入Token
           USER.signin(req.body).then(function (ret) {
               ret = JSON.parse(JSON.stringify(ret));
               ret.data._token = _token;
               ret.data._url =  url;
               ret.data._app = {}; //记录已经登录的
               ret.data._app[_app] = "";
               if( myCache.set(_token,ret.data)){
                   res.send(ret);
               }else{
                   res.send(VCODE.cache);
               }
           }).catch(function (ret) {
               res.send(ret);
           })
       }else{
           res.send(VCODE.forbid);
       }

    }else{
        res.send(VCODE.forbid);
    }
});

//token校验
router.post('/api/token/check', function(req, res, next) {

    var _token = req.body._token;
    var _sessionId = req.body._sessionid;
    var _app = req.body._app;
    var data = myCache.get(_token);

    if(data && VALID[_app] && _sessionId && data._app[_app] !== undefined){
        data._app[_app] = _sessionId;
        myCache.set(_token,data);
        var result = Object.assign({data:data},VCODE.success);
        res.send(result);
    }else{
        res.send(VCODE.token);
    }
});

//子服务的img图片,保持session
router.get('/api/img/session', function(req, res, next) {
    var _token = req.query._token;
    if(myCache.get(_token)){
        req.session.token = _token;
    }else{
        req.session.token = null;
    }
    console.log("img:",_token);
    res.send("ok");
});


//退出登录
router.post('/api/loginout', function(req, res, next) {
    var _token = req.body._token;
    var _app = req.body._app;
    var data = myCache.get(_token);
    //需要删除
    if(data){
        myCache.del(_token);
        //需要对所有的子系统进行退出操作
        COMM.loginOut(data._app,_app);
        res.send(VCODE.success);
    }else{
        res.send(VCODE.loginOut);
    }
});





module.exports = router;
